package com.cc.screen;

import org.bytedeco.ffmpeg.global.avcodec;
import org.bytedeco.ffmpeg.global.avutil;
import org.bytedeco.javacv.*;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
/**
 * @author gmli
 * @version V1.0
 **/
public class Image2Mp4 {
    public static void main(String[] args) throws Exception {
        //合成的MP4
        String mp4SavePath = "E:\\video\\img.mp4";
        //图片地址 这里面放了22张图片
        String img = "E:\\video\\bb";
        int width = 1600;
        int height = 900;
        //读取所有图片
        File file = new File(img);
        File[] files = file.listFiles();
        Map<Integer, File> imgMap = new HashMap<Integer, File>();
        int num = 0;
        for (File imgFile : files) {

            //resizeImage16to9(imgFile,img+"/"+new Date().getTime() +".png");
            imgMap.put(num, imgFile);

            num++;
        }
        createMp4(mp4SavePath, imgMap, width, height,num);

        //mergeAudioAndVideo(mp4SavePath, "E:\\video\\text.wav", "E:\\video\\out.mp4");
    }

    private static void createMp4(String mp4SavePath, Map<Integer, File> imgMap, int width, int height,int num) throws FrameRecorder.Exception {
        //视频宽高最好是按照常见的视频的宽高  16：9  或者 9：16
        FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(mp4SavePath, width, height);
        //设置视频编码层模式
        recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264);
        //设置视频为25帧每秒
        recorder.setFrameRate(25);
        //设置视频图像数据格式
        recorder.setPixelFormat(avutil.AV_PIX_FMT_YUV420P);
        recorder.setFormat("mp4");
        try {
            recorder.start();
            Java2DFrameConverter converter = new Java2DFrameConverter();
            //录制一个22秒的视频
            for (int i = 0; i < num; i++) {
                BufferedImage read = ImageIO.read(imgMap.get(i));
                //一秒是25帧 所以要记录25次
                for (int j = 0; j < 25; j++) {
                    recorder.record(converter.getFrame(read));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //最后一定要结束并释放资源
            recorder.stop();
            recorder.release();
        }
    }

    public static boolean mergeAudioAndVideo(String videoPath, String audioPath, String outPut) throws Exception {
        boolean isCreated = true;
        File file = new File(videoPath);
        if (!file.exists()) {
            return false;
        }
        FrameRecorder recorder = null;
        FrameGrabber grabber1 = null;
        FrameGrabber grabber2 = null;
        try {
            //抓取视频帧
            grabber1 = new FFmpegFrameGrabber(videoPath);
            //抓取音频帧
            grabber2 = new FFmpegFrameGrabber(audioPath);
            grabber1.start();
            grabber2.start();
            //创建录制
            recorder = new FFmpegFrameRecorder(outPut,
                    grabber1.getImageWidth(), grabber1.getImageHeight(),
                    grabber2.getAudioChannels());

            recorder.setFormat("mp4");
            recorder.setFrameRate(grabber1.getFrameRate());
            recorder.setSampleRate(grabber2.getSampleRate());
            recorder.start();

            Frame frame1;
            Frame frame2 ;
            //先录入视频
            while ((frame1 = grabber1.grabFrame()) != null ){
                recorder.record(frame1);
            }
            //然后录入音频
            while ((frame2 = grabber2.grabFrame()) != null) {

                recorder.record(frame2);
            }
            grabber1.stop();
            grabber2.stop();
            recorder.stop();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (recorder != null) {
                    recorder.release();
                }
                if (grabber1 != null) {
                    grabber1.release();
                }
                if (grabber2 != null) {
                    grabber2.release();
                }
            } catch (FrameRecorder.Exception e) {
                e.printStackTrace();
            }
        }
        return isCreated;

    }

    public static Frame drawText(Frame frame, String text) {
        Java2DFrameConverter converter = new Java2DFrameConverter();
        BufferedImage image = converter.getBufferedImage(frame);
        Graphics2D g2d = (Graphics2D) image.getGraphics();

        g2d.setColor(Color.RED); // 设置文字颜色为红色
        g2d.setFont(new Font("宋体", Font.BOLD, 30)); // 设置字体样式
        g2d.drawString(text, frame.imageHeight - 50, frame.imageHeight-50); // 绘制文本，x=50, y=50
         System.out.println(text);
        // 将处理后的图像转回Frame
        frame = converter.convert(image);
        return frame;

    }

    public static void resizeImage16to9(File inputFile, String outputFile) throws IOException {
        // 读取原始图片
        BufferedImage originalImage = ImageIO.read(inputFile);


        // 计算新的宽度和高度以符合16:9比例
        double originalWidth = originalImage.getWidth();
        double originalHeight = originalImage.getHeight();
        double targetAspectRatio = 9.0 / 16;
        double targetHeight = originalWidth * targetAspectRatio;

        // 创建一个新的图片，宽度不变，高度为计算出的高度
        BufferedImage resizedImage = new BufferedImage((int) originalWidth, (int) targetHeight, originalImage.getType());
        resizedImage.getGraphics().drawImage(originalImage.getScaledInstance((int) originalWidth, (int) targetHeight, BufferedImage.SCALE_SMOOTH), 0, 0, null);

        // 写入调整大小后的图片
        ImageIO.write(resizedImage, "jpg", new File(outputFile));

    }
}
